import { OperLog, LoginInfo } from '@/models/system';
import operLogService from '@/services/system/operLog.service';
import loginInfoService from '@/services/system/loginInfo.service';
import { getClientIp, getAddressByIp } from '../ip/ip.util';
import { getUserAgent } from '../browser/user-agent.util';
import { getLogger } from '../logger';

const logger = getLogger('sys-async');

/**
 * 异步工厂类，用于产生异步任务
 */
class AsyncFactory {
  /**
   * 记录登录信息
   * @param username 用户名
   * @param status 状态
   * @param message 消息
   * @param args 列表
   * @returns 任务函数
   */
  public static recordLogininfor(username: string, status: string, message: string, ...args: any[]): () => void {
    const ip = getClientIp();
    const userAgent = getUserAgent();
    
    return async () => {
      try {
        const address = await getAddressByIp(ip);
        
        // 记录到日志文件
        logger.info(`[${ip}][${address}][${username}][${status}][${message}]`, ...args);
        
        // 获取客户端信息
        const { os, browser } = userAgent;
        
        // 封装登录日志对象并记录到数据库
        const loginInfo = {
          userName: username,
          status: status === 'Success' ? LoginInfo.STATUS.SUCCESS : LoginInfo.STATUS.FAIL,
          ipaddr: ip,
          loginLocation: address,
          browser: `${browser.name} ${browser.version}`,
          os: `${os.name} ${os.version}`,
          msg: message,
          loginTime: new Date()
        };
        
        // 保存登录日志
        await loginInfoService.insertLoginInfo(loginInfo);
      } catch (error) {
        logger.error('记录登录信息异常', error);
      }
    };
  }

  /**
   * 操作日志记录
   * @param operLog 操作日志信息
   * @returns 任务函数
   */
  public static recordOper(operLog: Partial<OperLog>): () => void {
    return async () => {
      try {
        // 查询IP地址位置信息
        if (operLog.operIp) {
          operLog.operLocation = await getAddressByIp(operLog.operIp);
        }
        
        // 保存日志记录
        await operLogService.insertOperlog(operLog);
      } catch (error) {
        logger.error('记录操作日志异常', error);
      }
    };
  }
}

export default AsyncFactory; 